package models

import (
	"errors"
	"fmt"
	"reflect"
	"strings"
	"time"

	"github.com/astaxie/beego/orm"
)

type FlowProcess struct {
	Id         int64     `orm:"column(id);pk"`
	Code       string    `orm:"column(code);null"`
	Name       string    `orm:"column(name);null"`
	Version    int64     `orm:"column(version);null"`
	Xmldata    string    `orm:"column(xmldata);null"`
	Remark     string    `orm:"column(remark);null"`
	Flag       int       `orm:"column(flag);null"`
	Parentid   int64     `orm:"column(parentid);null"`
	Status     int       `orm:"column(status);null"`
	Createdate time.Time `orm:"column(createdate);type(date);null"`
	Updatedate time.Time `orm:"column(updatedate);type(date);null"`
	Isdelete   int16     `orm:"column(isdelete);null"`
	Tenant     int64     `orm:"column(tenant);null"`
}

type FlowProcessLst struct {
	Id         int64     `orm:"column(id);pk"`
	Code       string    `orm:"column(code);null"`
	Name       string    `orm:"column(name);null"`
	Version    int64     `orm:"column(version);null"`
	Remark     string    `orm:"column(remark);null"`
	Flag       int       `orm:"column(flag);null"`
	Parentid   int64     `orm:"column(parentid);null"`
	Status     int       `orm:"column(status);null"`
	Isdelete   int16     `orm:"column(isdelete);null"`
	Tenant     int64     `orm:"column(tenant);null"`
}

func (t *FlowProcess) TableName() string {
	return "t_flow_process"
}

func init() {
	orm.RegisterModel(new(FlowProcess))
}

// AddTFlowProcess insert a new TFlowProcess into database and returns
// last inserted Id on success.
func AddTFlowProcess(m *FlowProcess) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

func GetFlowProcessByCode(code string)(v *FlowProcess,err error)  {
	o := orm.NewOrm()
	v = &FlowProcess{}
	err = o.QueryTable("t_flow_process").Filter("status",1).Filter("code",code).One(v)
	return v,err
}

// GetTFlowProcessById retrieves TFlowProcess by Id. Returns error if
// Id doesn't exist
func GetTFlowProcessById(id int64) (v *FlowProcess, err error) {
	o := orm.NewOrm()
	v = &FlowProcess{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetProcessByCondition(query map[string]string) ([]FlowProcess, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(FlowProcess))
	condition := orm.NewCondition()
	enum := 0
	for k, v := range query {
		if strings.Contains(k, "Condition_Join") {
			if strings.Contains(v, "or") {
				enum = 1
			}

		} else {
			k = strings.Replace(k, ".", "__", -1)
			if strings.Contains(k, "isnull") {
				if enum == 0 {
					condition = condition.And(k, (v == "true" || v == "1"))
				}
				if enum == 1 {
					condition = condition.Or(k, (v == "true" || v == "1"))
				}
			} else {
				if enum == 0 {
					condition = condition.And(k, v)
				}
				if enum == 1 {
					condition = condition.Or(k, v)
					enum = 0
				}
			}
		}
	}
	qs = qs.SetCond(condition)
	result := []FlowProcess{}
	_, err := qs.OrderBy("-version").All(&result)
	if err != nil {
		return nil, err
	} else {
		return result, nil
	}
}

func GetAllFlowProcessList(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []FlowProcessLst, count int64, err error) {
	o := orm.NewOrm()
	var list  []FlowProcessLst
	var args []interface{}
	sql := "SELECT " +
    		"P.* " +
    	"FROM " +
    		"PUBLIC.T_FLOW_PROCESS P " +
    	"WHERE " +
    		"P.VERSION = ( SELECT MAX( B.VERSION ) FROM PUBLIC.T_FLOW_PROCESS B WHERE P.CODE = B.CODE) "
	flg := 0
	for key,value := range query {
		if flg == 0 {
			sql += "AND (P." + key + " = ? "
		}else if flg == len(query) - 1{
			sql += "OR P." + key + " =? )"
		}else{
			sql += "OR P." + key + " =? "
		}
		flg += 1
		args = append(args,value)
	}
	count, _ = o.Raw(sql,args).QueryRows(&list)
	if err != nil {
		return list,count,err
	}else{
		sql += " limit  ? offset  ?"
		args = append(args,10)
		args = append(args,0)
		o.Raw(sql,args).QueryRows(&list)
		return list,count,nil
	}
}

// GetAllTFlowProcess retrieves all TFlowProcess matches certain condition. Returns empty list if
// no records exist
func GetAllTFlowProcess(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, count int64, err error) {
	o := orm.NewOrm()
	condition := orm.NewCondition()
	qs := o.QueryTable(new(FlowProcess))
	enum := 0
	for k, v := range query {
		if strings.Contains(k, "Condition_Join") {
			if strings.Contains(v, "or") {
				enum = 1
			}

		} else {
			k = strings.Replace(k, ".", "__", -1)
			if strings.Contains(k, "isnull") {
				if enum == 0 {
					condition = condition.And(k, (v == "true" || v == "1"))
				}
				if enum == 1 {
					condition = condition.Or(k, (v == "true" || v == "1"))
				}
			} else {
				if enum == 0 {
					condition = condition.And(k, v)
				}
				if enum == 1 {
					condition = condition.Or(k, v)
					enum = 0
				}
			}
		}
	}
	qs = qs.SetCond(condition)
	count, _ = qs.Count()
	/* qs := o.QueryTable(new(FlowProcess))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		if strings.Contains(k, "isnull") {
			qs = qs.Filter(k, (v == "true" || v == "1"))
		} else {
			qs = qs.Filter(k, v)
		}
	}*/
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, 0, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, 0, errors.New("Error: unused 'order' fields")
		}
	}

	var l []FlowProcess
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, count, nil
	}
	return nil, 0, err
}

func RecoverOrHangupProcess(id int64)(err error)  {
	o := orm.NewOrm()
	v := FlowProcess{Id: id}
	if err = o.Read(&v); err == nil {
		var num int64
		// 已挂起  先更新其他版本为挂起 然后在更新当前版本为 进行中
		if v.Status == 0 {
			v.Status = 1
			o.QueryTable(v.TableName()).Filter("code",v.Code).Update(orm.Params{
				"status": 0,
			})
			o.Update(&v)
		}else{
			// 进行中 直接更改为挂起状态
			v.Status = 0
			if num, err = o.Update(&v,"status"); err == nil {
				fmt.Println("Number of records updated in database:", num)
			}
		}
	}
	return
}

// UpdateTFlowProcess updates TFlowProcess by Id and returns error if
// the record to be updated doesn't exist
func UpdateTFlowProcessById(m *FlowProcess) (err error) {
	o := orm.NewOrm()
	v := FlowProcess{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteTFlowProcess deletes TFlowProcess by Id and returns error if
// the record to be deleted doesn't exist
func DeleteTFlowProcess(id int64) (err error) {
	o := orm.NewOrm()
	v := FlowProcess{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&FlowProcess{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}
